/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */


package com.huawei.api.handler;

import com.huawei.api.bean.ClientParameter;
import com.huawei.api.bean.Rule;
import com.huawei.api.builder.RuleCfgBuilder;
import com.huawei.api.exception.BaseCustomerException;
import com.huawei.api.utils.FileUtil;

import lombok.Data;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 规则处理
 *
 * @since 2023/10/28
 */
@Data
public class RuleHandler implements Handler {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileHandler.class);

    private final ClientParameter clientParameter;

    private final Set<String> checkers;

    private final RuleCfgBuilder ruleCfgBuilder;

    public RuleHandler(ClientParameter clientParameter, RuleCfgBuilder ruleCfgBuilder) {
        this.clientParameter = clientParameter;
        this.checkers = new HashSet<>();
        this.ruleCfgBuilder = ruleCfgBuilder;
    }

    @Override
    public void handle() throws BaseCustomerException {
        // 加载规则文件
        List<Rule> customRules = ruleCfgBuilder.getCustomeRules();
        if (customRules.size() > 0) {
            checkers.addAll(customRules.stream().map(Rule::getChecker).collect(Collectors.toSet()));
        }
        String checker = clientParameter.getChecker();
        if (StringUtils.isNoneBlank(checker)) {
            String checkerStr = FileUtil.readTxtToString(checker);
            LOGGER.info("<<< RuleHandler handle read check = {}", checkerStr);
            if (StringUtils.isNoneBlank(checkerStr)) {
                checkers.addAll(Arrays.asList(checkerStr.split("\n")));
            }
        }
    }
}
